import { categoryGet, categoryPost, ICateParams } from "@/api/course";
import { Button, Form, Input, Select } from "antd";
import React, { useEffect, useState, Dispatch, SetStateAction } from "react";

const { Option } = Select;

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
interface ICatePubProps {
  setIsModalOpen: Dispatch<SetStateAction<boolean>>;
  handleDataClose: (cateObj: ICateParams) => void;
}
const CatePublic: React.FC<ICatePubProps> = (props) => {
  const [form] = Form.useForm();
  const [fatherList, setFatherList] = useState<ICateParams[]>([]);
  useEffect(() => {
    categoryGet().then((res) => {
      setFatherList(res.data.results);
    });
  }, []);

  const onFinish = (values: any) => {
    console.log(values);
    categoryPost(values).then((res) => {
      // console.log(res);
      // 方法1：只能关闭遮罩，
      // props.setIsModalOpen(false);
      // 方法2：关闭遮罩，在表格中实时显示新数据
      props.handleDataClose({
        ...values,
        status: true,
        objectId: res.data.objectId,
      });
    });
  };

  const onReset = () => {
    form.resetFields();
  };

  return (
    <Form
      {...layout}
      form={form}
      name="control-hooks"
      onFinish={onFinish}
      style={{ maxWidth: 600 }}
    >
      <Form.Item name="cateName" label="分类名称" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="fatherId" label="父级分类" rules={[{ required: true }]}>
        <Select placeholder="请选择父级分类" allowClear>
          <Option value="0-0">顶级分类</Option>
          {fatherList.map((item) => {
            return (
              <Option key={item.objectId} value={item.objectId}>
                {item.cateName}
              </Option>
            );
          })}
        </Select>
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
        <Button htmlType="button" onClick={onReset}>
          重置
        </Button>
      </Form.Item>
    </Form>
  );
};

export default CatePublic;
